package no.weather;

import no.weather.weatherProvider.WeatherDatabase;
import no.weather.weatherProvider.WeatherProvider;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class WeatherStationsView extends ListActivity {
	public static final String SHOW_FAVORITE_ONLY = "show favorite";
	private Cursor mCursor;
	private WeatherProvider provider;
	private boolean mFavoritesOnly;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		provider = new WeatherProvider(getApplicationContext());

		mFavoritesOnly = getIntent().getExtras().getBoolean(
				SHOW_FAVORITE_ONLY);
		showStations();

	}

	/**
	 * 
	 */
	private void showStations() {
		if (!mFavoritesOnly) {
			mCursor = provider.getAllStations(WeatherDatabase.STATION_NAME);
		} else {
			mCursor = provider
					.getFavoriteStations(WeatherDatabase.STATION_NAME);
		}
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.station_list_item, mCursor,
				new String[] { WeatherDatabase.STATION_NAME },
				new int[] { R.id.stationName });

		// adapter.setFilterQueryProvider(new Filter());
		setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		mCursor.moveToPosition(position);
		Intent intent = new Intent(this, WeatherReportView.class);
		intent.putExtra(WeatherDatabase.STATION_ID, mCursor.getString(mCursor
				.getColumnIndex(WeatherDatabase.STATION_ID)));
		intent.putExtra(WeatherDatabase.STATION_PROVIDER, mCursor
				.getString(mCursor
						.getColumnIndex(WeatherDatabase.STATION_PROVIDER)));
		startActivityForResult(intent, -1);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_CANCELED)
			showStations();
			
	}

	/*
	 * TODO: add filter to view private class Filter implements
	 * FilterQueryProvider {
	 * 
	 * @Override public Cursor runQuery(CharSequence constraint) { return
	 * provider.getAllStations(WeatherDatabase.STATION_NAME, constraint); }
	 * 
	 * }
	 */
}
